import { PAGE_TYPE, COMPONENT_TYPES, POSITION_TYPE, BG_POSITION_REPEAT_TYPES_MAP } from '@/common/const'
import { WB_ITEM_LISTS } from '@/common/const-wb'
import store from '@/store'
import { H5_TYPE, MOBILE_WID_HEI } from '@/common/const-dif'
import { WB_LISTS_CONTROL_ID } from '@/common/const-wb'
import { isHasOwnProperty } from '@/plugins/utils'
import { ComponentTypes} from '@/store/default-styles'
import { ADD_COMP_ATTR } from '@/store/default-styles-dom'
import { SAVE_IMG_DATA_TYPES } from '@/common/events'

const DELETE_CON_STYLES_ATTR = ['width','height','top','left']

export const remUnit = 7.5
export function getComponentDataByCid(cid) {
  return ComponentTypes[cid];
}
export function dealCompatibilityData(componentData) {
  if(componentData.cid == COMPONENT_TYPES.wb_btn) {
    if(!componentData.bgUrl) {
      componentData.selectedBGUrl = ""
    }
  } else if(componentData.cid == COMPONENT_TYPES.wb_upload || componentData.cid == COMPONENT_TYPES.wb_camera) {
    if(!isHasOwnProperty(componentData.commonAttr, 'saveImgType')) {
      componentData.commonAttr.saveImgType = SAVE_IMG_DATA_TYPES[0].value;
      componentData.commonAttr.saveImgQuality = 0.8;
    }
  } 
  if(!isHasOwnProperty(componentData, "events")) {
    componentData.events = {}
  }

  let oriComponentData = getComponentDataByCid(componentData.cid);
  _.forEach(oriComponentData, (value, key) => {
    if(_.isObject(oriComponentData[key])){
      let oriCommonAttr = {}
      _.merge(oriCommonAttr, ADD_COMP_ATTR.commonAttr);
      _.merge(oriCommonAttr, oriComponentData.commonAttr);
      let conStyles = componentData.conStyles || {};
      let conAttr = componentData.conAttr;
      let commonAttr = componentData.commonAttr;

      if(key == "conAttr") {
        _.forEach(DELETE_CON_STYLES_ATTR, (key) => {
          conStyles[key] = conAttr[key] + "px"
        })
      } else if(key == "commonAttr") {
        _.forEach(oriCommonAttr, (value, key) => {
          if(!isHasOwnProperty(commonAttr, key)){
            commonAttr[key] = value
          }
        })
      }
    }else if(!isHasOwnProperty(componentData, key)){
      componentData[key] = value
    }
  })
  // 递归恢复删除字段
  if(componentData.btn) {
    dealCompatibilityData(componentData.btn)
  }

  //修改属性名
  // const commonAttr = componentData.commonAttr;
  // if(isHasOwnProperty(commonAttr, "relateCompId")){
  //   componentData.commonAttr.relateAttrCompId = componentData.commonAttr.relateCompId;
  //   delete componentData.commonAttr.relateCompId
  // }
  // if(isHasOwnProperty(commonAttr, "colorType")){
  //   componentData.commonAttr.borderColor = componentData.commonAttr.colorType;
  //   componentData.commonAttr.backgroundColor = componentData.commonAttr.backgroundColorType;
  //   delete componentData.commonAttr.colorType;
  //   delete componentData.commonAttr.backgroundColorType;
  // }
  // if(!isHasOwnProperty(commonAttr, 'relateAttrCompId')){
  //   componentData.commonAttr.relateAttrCompId = '';
  // }
  // if(componentData.cid == COMPONENT_TYPES.wb_camera){
  //   if(isHasOwnProperty(commonAttr, "deleteButtonSize")){
  //     componentData.commonAttr.delButtonSize = componentData.commonAttr.deleteButtonSize;
  //     delete componentData.commonAttr.deleteButtonSize;
  //   }
  //   if(isHasOwnProperty(commonAttr, "fileSizeLimit")){
  //     componentData.commonAttr.fSizeLimit = componentData.commonAttr.fileSizeLimit;
  //     delete componentData.commonAttr.fileSizeLimit;
  //   }
  // }else if(componentData.cid == COMPONENT_TYPES.wb_radio || componentData.cid == COMPONENT_TYPES.wb_checkbox){
  //   if(isHasOwnProperty(commonAttr, "itemMarginLR")){
  //     componentData.commonAttr.itemMarginL = componentData.commonAttr.itemMarginLR;
  //     componentData.commonAttr.itemMarginR = componentData.commonAttr.itemMarginLR;
  //     componentData.commonAttr.itemPaddingL = componentData.commonAttr.itemPaddingLR;
  //     componentData.commonAttr.itemPaddingR = componentData.commonAttr.itemPaddingLR;
  //     delete componentData.commonAttr.itemMarginLR;
  //     delete componentData.commonAttr.itemPaddingLR;
  //   }

  //   if(componentData.cid == COMPONENT_TYPES.wb_checkbox){
  //     if(!isHasOwnProperty(commonAttr, "shape")){
  //       componentData.commonAttr.shape = "square"
  //     }
  //   }
  // }
}
const UNIT_TRANSFORM_ATTRS = [ 
  "fontSize", "letterSpacing", "topDistance", "bottomDistance",
  "left", "right", "bottom", "top",
  "width", "height", 
  "paddingLR", "paddingTB", "percentPaddingTB", "percentPaddingLR", 
  "marginLR", "marginTB", 
  "borderRadius", "borderSize", "itemBorderRadius", "itemBorderSize",
]
const UNIT_TRANSFORM_ITEM_ATTRS = [
  "itemWidth", "itemHeight", "itemPicWidth", "itemPicHeight", 
  "itemPaddingTB", "itemPaddingL", "itemPaddingR", "itemPaddingLR",
  "itemMarginTB", "itemMarginL", "itemMarginR", "itemMarginLR"
]
// const UNIT_TRANSFORM_H_ATTRS = ["left", "right", "width"]
// const UNIT_TRANSFORM_V_ATTRS = ["top", "bottom", "height"]
export function pageAdaptive(componentData, pageType){
  let commonAttr = componentData.commonAttr
  if(componentData.cid == COMPONENT_TYPES.wb_img){
    let filter = commonAttr.filter
    if(filter){
      filter.blur = pxTovw(filter.blur)
      filter.offsetX = pxTovw(filter.offsetX)
      filter.offsetY = pxTovw(filter.offsetY)
      filter.blurRadius = pxTovw(filter.blurRadius)
    }
  }
  let attrs = UNIT_TRANSFORM_ATTRS;
  if(WB_ITEM_LISTS.indexOf(componentData.cid) != -1){
    attrs = _.concat(attrs, UNIT_TRANSFORM_ITEM_ATTRS);
  }
  unitTransform(componentData.styles, attrs);
  unitTransform(componentData.conStyles, attrs);
  if(pageType == PAGE_TYPE.single && componentData.cid == COMPONENT_TYPES.group_component && componentData.commonAttr.isPercent){
    dealGroupComponentPercent(componentData)
  }else{
    if(!componentData.conStyles) {
      componentData.conStyles = {}
    }
    componentData.conStyles.top = getPxOVwByValue(componentData.conAttr.top)
  }
  // unitTransformPosition(componentData.conStyles);
  // unitTransform(componentData.conAttr);
  unitTransform(componentData.commonAttr, attrs);

  _.forEach(componentData.commonAttr, (val) => {
    if(_.isObject(val)){
      unitTransform(val, attrs);
    }
  })

  let btns = ["btn"];
  _.forEach(btns, (attr) => {
    if(componentData[attr]){
      pageAdaptive(componentData[attr], pageType)
    }
  })
}
// function unitTransformPosition(obj){
//   _.forEach(UNIT_TRANSFORM_H_ATTRS, (attr) => {
//     if(obj[attr]){
//       obj[attr] = obj[attr].split('px')[0]/MOBILE_WID_HEI.width * 100 + 'vw';
//     }
//   })
//   _.forEach(UNIT_TRANSFORM_V_ATTRS, (attr) => {
//     if(obj[attr]){
//       obj[attr] = obj[attr].split('px')[0]/MOBILE_WID_HEI.height * 100 + 'vh';
//     }
//   })
// }
function unitTransform(obj, attrs){
  if(!obj){
    return
  }
  _.forEach(attrs, (attr) => {
    if(obj[attr]){
      if(attr == "borderSize" || attr == "itemBorderSize"){
        if(obj[attr]%2 == 1){
          obj[attr] = obj[attr]+1;
        }
        obj.borderSize_ = parseInt(parseFloat(obj[attr]).toFixed(0));
      }else if(attr == "fontSize"){
        obj.fontSize_ = parseInt(parseFloat(obj[attr]).toFixed(0));
      }
      obj[attr] = pxTovw(obj[attr])
    }
  })
}
function dealGroupComponentPercent(componentData) {
  let hei = componentData.conAttr.height;
  componentData.conStyles.height = "100vh";
  _.forEach(componentData.components, (componentData_, index) => {
    componentData_.conStyles.top =  componentData_.conAttr.top/hei * 100 + "vh";
    componentData_.conStyles.height =  componentData_.conAttr.height/hei * 100 + "vh";
  })
}
export function dealPosition(componentData, fixedComps, pageAttrs){
  let commonAttr = componentData.commonAttr
  if(commonAttr.isPageFixed){
    componentData.conStyles.position = "fixed"
    if(componentData.conAttr.left < 4){
      delete componentData.conStyles.left
    }
    componentData.conStyles.zIndex = 100
    fixedComps.push(componentData)
  }
  let left = 0;
  let top = 0;
  let reallyHeight = MOBILE_WID_HEI.clientHeight*MOBILE_WID_HEI.adaptiveScale
  if(MOBILE_WID_HEI.adaptiveScale <= 1 && !store.state.siteInfo.md.isMobile) {
    reallyHeight = MOBILE_WID_HEI.clientHeight
    if(reallyHeight < pageAttrs.height) {
      reallyHeight = pageAttrs.height
    }
  }
  switch(commonAttr.positionType){
    case POSITION_TYPE.no:
      if(commonAttr.isBottom){
        let bottom = MOBILE_WID_HEI.height - (componentData.conAttr.top + componentData.conAttr.height)
        if(bottom < 0){
          bottom = 0;
        }
        top = reallyHeight - bottom - componentData.conAttr.height
        componentData.conStyles.top = getPxOVwByValue(top)
        componentData.conAttr.top = top
      }
      if(commonAttr.isRight){
        left = MOBILE_WID_HEI.width - (componentData.conAttr.width + componentData.commonAttr.right)
        componentData.conStyles.left = getPxOVwByValue(left);
        componentData.conAttr.left = left
      }
    break;
    case POSITION_TYPE.top:
      componentData.conStyles.top = "0"
      componentData.conAttr.top = 0
    break;
    case POSITION_TYPE.bottom:
      top = (reallyHeight - componentData.conAttr.height)
      componentData.conStyles.top = getPxOVwByValue(top)
      componentData.conAttr.top = top
    break;
    case POSITION_TYPE.left:
      componentData.conStyles.left = "0"
      componentData.conAttr.left = 0
    break;
    case POSITION_TYPE.right:
      left = MOBILE_WID_HEI.width - componentData.conAttr.width;
      componentData.conStyles.left = getPxOVwByValue(left);
      componentData.conAttr.left = left
    break;
    case POSITION_TYPE.leftTop:
      componentData.conStyles.left = "0"
      componentData.conAttr.left = 0
      componentData.conStyles.top = "0"
      componentData.conAttr.top = 0
    break;
    case POSITION_TYPE.rightTop:
      left = MOBILE_WID_HEI.width - componentData.conAttr.width
      componentData.conStyles.left = getPxOVwByValue(left);
      componentData.conAttr.left = left
      componentData.conStyles.top = "0"
      componentData.conAttr.top = 0
    break;
    case POSITION_TYPE.leftBottom:
      componentData.conStyles.left = "0"
      componentData.conAttr.left = 0
      top = (reallyHeight - componentData.conAttr.height)
      componentData.conStyles.top = getPxOVwByValue(top)
      componentData.conAttr.top = top
    break;
    case POSITION_TYPE.rightBottom:
      left = MOBILE_WID_HEI.width - componentData.conAttr.width
      componentData.conStyles.left = getPxOVwByValue(left);
      componentData.conAttr.left = left
      top = (reallyHeight - componentData.conAttr.height)
      componentData.conStyles.top = getPxOVwByValue(top)
      componentData.conAttr.top = top
    break;
    case POSITION_TYPE.center:
      left = (MOBILE_WID_HEI.clientWidth*MOBILE_WID_HEI.adaptiveScale - componentData.conAttr.width)/2;
      componentData.conStyles.left = getPxOVwByValue(left)
      componentData.conAttr.left = left
      top = (reallyHeight - componentData.conAttr.height)/2
      componentData.conStyles.top = getPxOVwByValue(top)
      componentData.conAttr.top = top
    break;
  }

  if(commonAttr.isRelative){
    componentData.conStyles.position = "relative"
    delete componentData.conStyles.width
    // delete componentData.conStyles.height
    delete componentData.conStyles.top
    // delete componentData.conStyles.left
  }
}

export function bgPositionStyle(styles_, bgPositionRepeatType){
  styles_.backgroundRepeat = 'no-repeat';
  if(bgPositionRepeatType == BG_POSITION_REPEAT_TYPES_MAP.centerTop){
    styles_.backgroundPosition = 'top center';
    styles_.backgroundSize = 'cover';
  }else if(bgPositionRepeatType == BG_POSITION_REPEAT_TYPES_MAP.centerBottom){
    styles_.backgroundPosition = 'bottom center';
    styles_.backgroundSize = 'auto';
  }else if(bgPositionRepeatType == BG_POSITION_REPEAT_TYPES_MAP.repeatY){
    styles_.backgroundPosition = 'center';
    styles_.backgroundRepeat = 'repeat-y';
    styles_.backgroundSize = 'auto';
  }else if(bgPositionRepeatType == BG_POSITION_REPEAT_TYPES_MAP.whole){
    styles_.backgroundPosition = 'top center';
    styles_.backgroundSize = '100% 100%';
  }
}

function pxTovw(a) {
  const siteInfo = store.state.siteInfo
  const siteAttrs = store.state.attrs
  if(siteInfo.isH5Edit || !store.state.siteInfo.md.isMobile || siteAttrs.h5Type == H5_TYPE.pc || siteAttrs.h5Type == H5_TYPE.canvas){
    return a
  } else {
    let num = parseFloat(a).toFixed(0);
    let oddToEven = parseInt(num % 2) + parseInt(num);
    let b = oddToEven/remUnit;
    return "string" == typeof a && a.match(/px$/) && (b += "vw"),b
  }
}

export function convertCss(cssStr) {
  return cssStr.replace(/\d+px/g, function(a){
    let num = parseFloat(a).toFixed(0)
    let xx = parseInt(num % 2) + parseInt(num)
    let b =  xx / remUnit;
    return "string" == typeof a && a.match(/px$/) && (b += "vw"),b
  });
}

export function getPxOVwByValue(value){
  const siteInfo = store.state.siteInfo
  const siteAttrs = store.state.attrs
  let unit = ''
  if(siteInfo.isH5Edit || !store.state.siteInfo.md.isMobile || siteAttrs.h5Type == H5_TYPE.pc || siteAttrs.h5Type == H5_TYPE.canvas){
    unit = value + 'px'
  }else{
    unit = pxTovw(value) + 'vw'
  }
  return unit
}

export function getPxOrVw(){
  const siteInfo = store.state.siteInfo
  const siteAttrs = store.state.attrs
  let unit = ''
  if(siteInfo.isH5Edit || !store.state.siteInfo.md.isMobile || siteAttrs.h5Type == H5_TYPE.pc || siteAttrs.h5Type == H5_TYPE.canvas){
    unit = 'px'
  }else{
    unit = 'vw'
  }
  return unit
}


export function getMainListEventByEvents(events){
  let event
  let tempArr = []
  _.forEach(events, (event) => {
    if(event.controlId && event.controlId.length > 0 && WB_LISTS_CONTROL_ID.indexOf(event.controlId) != -1){
      tempArr.push(event)
    }
  })
  if(tempArr.length > 0){
    tempArr = _.sortBy(tempArr, (event) => { return event.index; });
    event = tempArr[0]
    //主事件是组件的第一个事件，是wblist值， controlId是组件的主事件id
  }
  return event
}

export function getMainWbDataEventByEvents(events){
  let event_
  let tempArr = []
  _.forEach(events, (event) => {
    if(event.controlId && event.controlId.length > 0){
      tempArr.push(event)
    }
  })
  if(tempArr.length > 0){
    tempArr = _.sortBy(tempArr, (event) => { return event.index; });
    event_ = tempArr[0]
    //主事件是组件的第一个事件，是wblist值， controlId是组件的主事件id
  }
  return event_
}


